package socket;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class MySQL {


    @Test
    public void mysqlSocket() throws IOException {

        Socket socket=new Socket("localhost",3306);
        byte[] bytes=new byte[1024];
        int len = socket.getInputStream().read(bytes);

        System.out.println(new String(bytes));

    }

    @Test
    public void mysqlSocketChannel() throws IOException {

        Selector selector=Selector.open();
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(new InetSocketAddress("localhost",3307));
        System.out.println("开始连接...");
//        Socket socket=channel.socket();
//        byte[] bytes=new byte[1024];
//        int len = socket.getInputStream().read(bytes);
//        System.out.println(new String(bytes));
        channel.register(selector, SelectionKey.OP_CONNECT);
        while (true){
            selector.select();
            System.out.println("接收到消息.");
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                iterator.remove();
                ByteBuffer bf=ByteBuffer.allocate(512);
                channel.read(bf);
                System.out.println(new String(bf.array()));

            }


        }
    }

}
